package com.zhongfl.crm.mail;

import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.mail.bean.MailMessage;
import com.zhongfl.crm.mail.enums.MailTypeEnum;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;


/**
 * 邮件发送工具类
 */
@Component
@Slf4j
public class MailServiceImpl implements MailService {

    //默认发件人(系统发送邮件)
    @Value("${spring.mail.username}")
    private String mailFrom;

    @Resource
    private JavaMailSenderImpl javaMailSender;

    @Resource
    private FreeMarkerConfig freeMarkerConfig;

    @Override
    public void send(MailMessage mailMessage) throws CRMException {
        if(Objects.isNull(mailMessage)) {
            throw new CRMException("邮件内容不允许为Null");
        }
        if (CollectionUtils.isEmpty(Arrays.asList(mailMessage.getTo()))) {
            throw new CRMException("邮件接收人不能为空");
        }
        send(mailMessage.getTo(), mailMessage.getSubject(), mailMessage.getTemplateEnum(), mailMessage.getModels(), mailMessage.getFiles());
    }

    /**
     * 发送邮件模板
     *
     * @param title        邮件标题
     * @param to           接受人
     * @param templateEnum 模板枚举
     * @param models       模板数据 key object
     * @param files        附件信息 key 文件名称, value 文件内容
     * @throws CRMException 发送错误信息
     */
    @Override
    public void send(String[] to, String title, MailTypeEnum templateEnum, Map<String, Object> models, Map<String, File> files) throws CRMException {
        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper helper;
        Template template;
        String html;

        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailFrom);
            helper.setTo(to);
            helper.setSubject(title);
            template = freeMarkerConfig.getConfiguration().getTemplate(templateEnum.getTemplate());
            html = FreeMarkerTemplateUtils.processTemplateIntoString(template, models);
            helper.setText(html, true);
            if (MapUtils.isNotEmpty(files)) {
                for (Map.Entry<String, File> entry : files.entrySet()) {
                    if (Objects.equals(entry.getKey(), "img")) {//key为img的作为静态图片资源嵌入邮件
                        helper.addInline(entry.getKey(), entry.getValue());
                    } else {//key不为img的作为附件
                        helper.addAttachment(entry.getKey(), entry.getValue());
                    }
                }
            }
            javaMailSender.send(message);
        } catch (Exception e) {
            log.error("发送邮件异常");
        }
    }
}
